<template>
  <div class="image-grid-container">
    <div class="image-grid" ref="gridRef">
      <ImageCard
        v-for="image in images"
        :key="image.path"
        :image="image"
        :folder-path="folderPath"
        @image-click="handleImageClick"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import ImageCard from './ImageCard.vue';

export default {
  name: 'ImageGrid',
  components: {
    ImageCard
  },
  props: {
    images: {
      type: Array,
      required: true
    },
    folderPath: {
      type: String,
      required: true
    }
  },
  setup(props, { emit }) {
    const gridRef = ref(null);

    const handleImageClick = (image) => {
      emit('image-click', image);
    };

    // 响应式网格布局
    const updateGridLayout = () => {
      if (!gridRef.value) return;
      
      const containerWidth = gridRef.value.offsetWidth;
      const columnWidth = 200; // 基础列宽
      const gap = 8; // 间距
      const columns = Math.max(1, Math.floor((containerWidth + gap) / (columnWidth + gap)));
      
      gridRef.value.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;
    };

    // 防抖处理窗口大小变化
    let resizeTimeout = null;
    const debouncedUpdateLayout = () => {
      if (resizeTimeout) {
        clearTimeout(resizeTimeout);
      }
      resizeTimeout = setTimeout(updateGridLayout, 100);
    };

    onMounted(() => {
      updateGridLayout();
      window.addEventListener('resize', debouncedUpdateLayout);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', debouncedUpdateLayout);
      if (resizeTimeout) {
        clearTimeout(resizeTimeout);
      }
    });

    return {
      gridRef,
      handleImageClick
    };
  }
};
</script>

<style scoped>
.image-grid-container {
  height: 100%;
  overflow-y: auto;
  padding: 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
  max-width: 100%;
}

/* 滚动条样式 */
.image-grid-container::-webkit-scrollbar {
  width: 8px;
}

.image-grid-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.image-grid-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.image-grid-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
